var http = require('http');
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');
var siteName="留言板2";
var ip = '127.0.0.1';
var port = '80';

var server = http.createServer(function (request, response) {
	response.statusCode = 200;
	var ext = request.url.substr(request.url.lastIndexOf('.')+1);
	var exts = {
		'html':'text/html',
		'css':'text/css',
		'js':'text/javaScripe',
		'jpg':'image/jpeg',
		'png':'image/png',
	}
	if (exts[ext]==null) {
		exts[ext]="text/plain"
	} 
	response.setHeader('Content-Type',exts[ext]);
	var data='404';
	var p=url.parse(request.url,true);
	if (p.pathname=='/index.html') {
		try{
			data = fs.readFileSync('.'+request.url,'utf8');
			data = data.replace(/%title/g,siteName);//g表示将内容全部替换掉
			item = fs.readFileSync('data.json','utf8');//返回回来一个字符串
			item = JSON.parse(item);
			var s=''
			for (var i = 0; i < item.length; i++) {
				s+='<div class="item">'
				s+='<h6>'+item[i].newname+'<span>'+item[i].time+'</span><a href="/delmessage?id='+i+'">删除</a></h6>'
				s+='<p>'+item[i].message+'</p>'
				s+='</div>'
			}
			data = data.replace(/%main/g,s);
		}catch(e){
		
		}
		response.write(data);
		response.end();
	}else if (p.pathname=='/form.html') {
		data = fs.readFileSync('.'+request.url,'utf8');
		response.write(data);
		response.end();
	}else if (p.pathname=='/addmessage'){
		/*data="提交成功";
		response.writeHead(302,{
			'Location':'/index.html'
		});
		other=p.query.other;
		message=p.query.message;
		item=JSON.parse(fs.readFileSync('data.json','utf8'));
		item.push({
			"newname":other,
			"time":new Date(),
			"message":message
		});
		item=JSON.stringify(item);
		fs.writeFileSync('data.json',item);*/
		var s = '';
		request.on('data', function(data){    
	        s += data;
	    });
	    request.on('end', function(data){    
	         s = querystring.parse(s);
	    	item=JSON.parse(fs.readFileSync('data.json','utf8'));
		    item.push({
				"newname":s.other,
				"time":new Date(),
				"message":s.message
			});
			fs.writeFileSync('data.json',JSON.stringify(item));
			response.writeHead(302,{
				'Location':'/index.html'
			});
			response.end();
	    });
	}else if (p.pathname=='/delmessage') {
		id=p.query.id;
		item=JSON.parse(fs.readFileSync('data.json','utf8'));
		item.splice(id,1);
		item=JSON.stringify(item);
		fs.writeFileSync('data.json',item);
		response.writeHead(302,{
			'Location':'/index.html'
		});
		response.write(data);
		response.end();
	}
})
server.listen(port);
console.log('Server running at http://%s:%d/',ip,port);